package com.zhiqianbao.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.AudioState;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserPhoneCheck;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.WorthPurseUtil;

import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;


/**
 * Created by 子龙 on 2017/4/7.
 */

public class ProcessActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout taobao_cunt_icon_icon;
    private TextView topbar_textview_title;
    private Button button_return;
    private TextView id_icon;
    private TextView zhima_icon;
    private TextView procee_icon;
    private TextView work_icon;
    private TextView tv_taobao;
    private TextView emergency_icon;
    private SharedPreferanceUtils sharedPreferanceUtils;
    private RelativeLayout rl_idcard;
    private RelativeLayout the_ontact;
    private RelativeLayout the_work;
    private RelativeLayout tv_yunying;
    private String uid;
    private String job_state;
    private String identity_state;
    private String telecom_state;
    private String taobao_state;
    private String emergency_contact_state;
    private String zhima_state;
    private View zhima_line;
    private RelativeLayout the_zhima;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process);
        initView();
        addListner();
    }

    private void addListner() {
            taobao_cunt_icon_icon.setOnClickListener(this);
            button_return.setOnClickListener(this);
            rl_idcard.setOnClickListener(this);
            tv_yunying.setOnClickListener(this);
            the_ontact.setOnClickListener(this);
            the_work.setOnClickListener(this);
            the_zhima.setOnClickListener(this);
    }

    private void initView() {
            sharedPreferanceUtils = new SharedPreferanceUtils(this);
            taobao_cunt_icon_icon = (RelativeLayout) findViewById(R.id.taobao_cunt_icon_icon);
            topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
            topbar_textview_title.setText(R.string.mine);
            button_return = (Button) findViewById(R.id.button_return);
            taobao_cunt_icon_icon = (RelativeLayout) findViewById(R.id.taobao_cunt_icon_icon);
            //身份证认证
            rl_idcard = (RelativeLayout) findViewById(R.id.rl_idcard);
            //身份证
            id_icon = (TextView) findViewById(R.id.id_icon);
            zhima_icon = (TextView) findViewById(R.id.zhima_icon);
            //运营商
            procee_icon = (TextView) findViewById(R.id.procee_icon);
            //工作信息
            work_icon = (TextView) findViewById(R.id.work_icon);
            //淘宝
            tv_taobao = (TextView) findViewById(R.id.tv_taobao);

            emergency_icon = (TextView) findViewById(R.id.emergency_icon);
            //运营
            tv_yunying = (RelativeLayout) findViewById(R.id.tv_yunying);
            //紧急联系人
            the_ontact = (RelativeLayout) findViewById(R.id.the_ontact);
            //工作信息
            the_work = (RelativeLayout) findViewById(R.id.the_work);
            //芝麻信用
            the_zhima = (RelativeLayout) findViewById(R.id.the_zhima);
            zhima_line = (View) findViewById(R.id.zhima_line);

            //芝麻开启状态,1开启，0未开启
            String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
            if (!TextUtils.isEmpty(zhimaOpenOrClose)) {
                if ("1".equals(zhimaOpenOrClose)) {
                    zhima_line.setVisibility(View.VISIBLE);
                    the_zhima.setVisibility(View.VISIBLE);
                } else {
                    zhima_line.setVisibility(View.GONE);
                    the_zhima.setVisibility(View.GONE);
                }
            }
    }

    private void initData() {
        String userId = sharedPreferanceUtils.getUserId();
        String token_process = sharedPreferanceUtils.getToken();
        if(Constants.LOGIN_USER == null){
            Intent intent = new Intent(ProcessActivity.this,
                    WorthPurseUtil.getZhiddActivity().getClass());
            startActivity(intent);
            finish();
        }
//        showShortToast1("出来了");
        //获取当前系统时间
        authState();
        }

    public void phoneCheck() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message phoneCheckMessage = new Message();
                Map<String, String> params = new HashMap<>();
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("phone",Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone()+ "" : "");
                //1.0.7
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/checkNew", params, ProcessActivity.this);
                if(!TextUtils.isEmpty(result)){
                    Log.i("ProcessActivity1",""+result);
                }
                else{
                    Log.i("ProcessActivity1","这是空");
                }
                if (StringUtils.isBlank(result)) {
                    phoneCheckMessage.what = 0;
                } else {
                    phoneCheckMessage.what = 1;
                    Result<UserPhoneCheck> data = Result.fromJson(result, UserPhoneCheck.class);
                    phoneCheckMessage.obj = data;
                }
                userPhoneCheckHandler.sendMessage(phoneCheckMessage);
            }
        }).start();
    }

    Handler userPhoneCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        Result<UserPhoneCheck> data = (Result<UserPhoneCheck>) msg.obj;
                        if (data == null) {
                            return;
                        }
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            UserPhoneCheck userPhoneCheck = data.getData();
                            //还没有进行手机验证，跳转到输入手机号信息的页面
                            if (userPhoneCheck == null) {
                                procee_icon.setText("认证失败");
                                procee_icon.setTextColor(getResources().getColor(R.color.red));
                                return;
                            }
                            //已经验证，但是需要进行下一步处理，跳转到下一步处理页面
                            String status = userPhoneCheck.getStatus() != null ?
                                    userPhoneCheck.getStatus() : "";
                            if (Constants.CALL_DETAILS_STATUS_DONE.equals(status)) {
                                procee_icon.setText("已认证");
                                tv_yunying.setEnabled(false);
                                procee_icon.setTextColor(getResources().getColor(R.color.blue));
                            }
                            else if(Constants.CALL_DETAILS_STATUS_TIMEOUT.equals(status)){
                                procee_icon.setText("认证失败");
                                procee_icon.setTextColor(getResources().getColor(R.color.red));

                            }
                            else if(Constants.CALL_DETAILS_STATUS_UPCFAILED.equals(status)){
                                procee_icon.setText("认证失败");
                                procee_icon.setTextColor(getResources().getColor(R.color.red));
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    catch (JsonIOException exception){

                    }
                    catch (NullPointerException exception){

                    }
                    break;
                case 0:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        closeWaitDialog();
        initData();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
    }
    @Override
    public void onClick(View v) {
           if(R.id.taobao_cunt_icon_icon==v.getId()) {
               //淘宝认证
               try {
                   if (!TextUtils.isEmpty(job_state)) {
                       if (job_state.equals("1") || job_state.equals("2")) {
                           startActivity(new Intent(ProcessActivity.this, TaoBaoActivity.class));
                           the_ontact.setEnabled(false);
                           the_work.setEnabled(false);
                       }
                   }
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
            else if(R.id.rl_idcard==v.getId()) {
                   if (!TextUtils.isEmpty(identity_state)) {
                       if (identity_state.equals("0") || identity_state.equals("3")) {
                           startActivity(new Intent(ProcessActivity.this, FirstTimeConfirmInfoProgressThreeZx.class));
                       }
                   }
           }
            else if(R.id.tv_yunying==v.getId()) {
                   try {
                       //运营商确认
                       if (!TextUtils.isEmpty(identity_state)) {
                           if (identity_state.equals("1") || identity_state.equals("2")) {
                               if (!TextUtils.isEmpty(telecom_state)) {
                                   if (telecom_state.equals("0") || telecom_state.equals("3") || telecom_state.equals("2")) {
                                       startActivity(new Intent(ProcessActivity.this, BindPhoneConfirmActivity.class));
                                   }
                               }
                           } else {
                               failReasonMsg();
                           }
                       }
                   } catch (Exception e) {

                   }
           }
            else if(R.id.the_ontact==v.getId()) {
                   try {
                       if (!TextUtils.isEmpty(telecom_state)) {
                           if (telecom_state.equals("1") || telecom_state.equals("2")) {
                               if (!TextUtils.isEmpty(emergency_contact_state)) {
                                   if (emergency_contact_state.equals("0") || emergency_contact_state.equals("3")) {
                                       startActivity(new Intent(ProcessActivity.this, ThirdActivity.class));
                                   }
                               }
                           } else {
                               failReasonMsg();
                           }
                       }
                   } catch (Exception e) {
                   }
           }
            else if(R.id.the_zhima==v.getId()) {
                   //芝麻信用
                   if (!TextUtils.isEmpty(zhima_state)) {
                       if (zhima_state.equals("0") || zhima_state.equals("3")) {
                           startActivity(new Intent(ProcessActivity.this, ZhiMaActivity.class));
                       }
                   }
           }
            else if(R.id.the_work==v.getId()) {
                   //工作信息
                   try {
                       if (!TextUtils.isEmpty(emergency_contact_state)) {
                           if (emergency_contact_state.equals("1") || emergency_contact_state.equals("2")) {
                               if (!TextUtils.isEmpty(job_state)) {
                                   if (job_state.equals("0") || job_state.equals("3")) {
                                       startActivityForResult(new Intent(ProcessActivity.this, FourthActivity.class), 5);
                                   }
                               }
                           } else {
                               failReasonMsg();
                           }
                       }
                   } catch (Exception e) {
                   }
           }
            else if(R.id.button_return==v.getId()){
                    finish();
            }

        }


    public void failReasonMsg(){
            final AlertDialog msgDialog = new AlertDialog.Builder(this, R.style.Dialog).create();
            msgDialog.show();
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_login_other_layout, null);
            msgDialog.getWindow().setContentView(view);
            Button button = (Button) view.findViewById(R.id.positiveButton);
            TextView msgTv = (TextView) view.findViewById(R.id.message);
            TextView titleTv = (TextView) view.findViewById(R.id.title);
            titleTv.setText("提示");
            msgTv.setText("请完成上步验证！");
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    msgDialog.dismiss();
                }
            });
    }

    public static final int DATA_FILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();

    private void authState(){
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/auth/authState",
                        mapParams, ProcessActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    AudioState data =gson.fromJson(result, AudioState.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FILED:
                    closeWaitDialog();
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case DATA_SCUESSFUL:
                    AudioState response = (AudioState) msg.obj;
                    //0：未完成；1：已认证；2：认证中；3：认证失败
                    closeWaitDialog();
                    if (response == null) {
                        showShortToast1("网络超时，请再试!");
//                    closeWaitDialog();
                    }
                    if (response != null) {
                        if (response.getCode().equals("0")) {
//                        closeWaitDialog();
                            AudioState.DataBean dataBean=response.getData();
                            if(dataBean==null){
                                return;
                            }
                            emergency_contact_state = dataBean.getEmergency_contact_state();
                            identity_state = dataBean.getIdentity_state();
                            job_state = dataBean.getJob_state();
                            taobao_state = dataBean.getTaobao_state();
                            telecom_state = dataBean.getTelecom_state();
                            zhima_state = dataBean.getZhima_state();
//                        Log.i("emergency_contact_state",emergency_contact_state);
                            sharedPreferanceUtils.setTelecon(telecom_state);
                            sharedPreferanceUtils.setTaoBao(taobao_state);
                            sharedPreferanceUtils.seteEmergency(emergency_contact_state);
                            sharedPreferanceUtils.setJobState(job_state);
                            sharedPreferanceUtils.setidCardState(identity_state);
                            sharedPreferanceUtils.setZhiMaState(zhima_state);


                            if (!TextUtils.isEmpty(zhima_state)) {
                                if (zhima_state.equals("0")) {
                                    zhima_icon.setText("未认证");
                                    zhima_icon.setTextColor(getResources().getColor(R.color.red));
                                } else if (zhima_state.equals("1")) {
                                    zhima_icon.setText("已认证");
                                    the_zhima.setEnabled(false);
                                    zhima_icon.setTextColor(getResources().getColor(R.color.blue));
                                } else if (zhima_state.equals("2")) {
                                    zhima_icon.setText("认证中");
                                    the_zhima.setEnabled(false);
                                } else if (zhima_state.equals("3")) {
                                    zhima_icon.setText("认证失败");
                                    zhima_icon.setTextColor(getResources().getColor(R.color.red));
                                } else {
                                    zhima_icon.setText("未认证");
                                    zhima_icon.setTextColor(getResources().getColor(R.color.red));
                                }
                            }
                            if (!TextUtils.isEmpty(identity_state)) {

                                if (!TextUtils.isEmpty(identity_state)) {
                                    if (identity_state.equals("0")) {
                                        id_icon.setText("未认证");
                                        id_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else if (identity_state.equals("1")) {
                                        id_icon.setText("已认证");
                                        rl_idcard.setEnabled(false);
                                        id_icon.setTextColor(getResources().getColor(R.color.blue));
                                    } else if (identity_state.equals("2")) {
                                        id_icon.setText("认证中");
                                        rl_idcard.setEnabled(false);
                                    } else if (identity_state.equals("3")) {
                                        id_icon.setText("认证失败");
                                        id_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        id_icon.setText("未认证");
                                        id_icon.setTextColor(getResources().getColor(R.color.red));
                                    }
                                } else {
                                    id_icon.setText("未认证");
                                    id_icon.setTextColor(getResources().getColor(R.color.red));
                                }

                                if (!TextUtils.isEmpty(telecom_state)) {
                                    if (telecom_state.equals("0")) {
                                        procee_icon.setText("未认证");
                                        procee_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else if (telecom_state.equals("1")) {
                                        procee_icon.setText("已认证");
                                        tv_yunying.setEnabled(false);
                                        procee_icon.setTextColor(getResources().getColor(R.color.blue));
                                    } else if (telecom_state.equals("2")) {
                                        procee_icon.setText("认证中");
                                        Log.i("ProcessActivity", "认证中");
                                        phoneCheck();
                                    } else if (telecom_state.equals("3")) {
                                        procee_icon.setText("认证失败");
                                        procee_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        procee_icon.setText("未认证");
                                        procee_icon.setTextColor(getResources().getColor(R.color.red));
                                    }
                                } else {
                                    procee_icon.setText("未认证");
                                    procee_icon.setTextColor(getResources().getColor(R.color.red));
                                }
                                if (!TextUtils.isEmpty(job_state)) {
                                    if (job_state.equals("0")) {
                                        work_icon.setText("未认证");
                                        work_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else if (job_state.equals("1")) {
                                        work_icon.setText("已认证");
                                        the_work.setEnabled(false);
                                        work_icon.setTextColor(getResources().getColor(R.color.blue));
                                    } else if (job_state.equals("2")) {
                                        work_icon.setText("认证中");
                                        the_work.setEnabled(false);
                                    } else if (job_state.equals("3")) {
                                        work_icon.setText("认证失败");
                                        work_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        work_icon.setText("未认证");
                                        work_icon.setTextColor(getResources().getColor(R.color.red));
                                    }
                                } else {
                                    work_icon.setText("未认证");
                                    work_icon.setTextColor(getResources().getColor(R.color.red));
                                }
                                if (!TextUtils.isEmpty(taobao_state) && !TextUtils.isEmpty(zhima_state)) {
                                    if (taobao_state.equals("0") || zhima_state.equals("0")) {
                                        tv_taobao.setText("未认证");
                                        tv_taobao.setTextColor(getResources().getColor(R.color.red));
                                    } else if (taobao_state.equals("1") && zhima_state.equals("1")) {
                                        tv_taobao.setText("已认证");
                                        taobao_cunt_icon_icon.setEnabled(false);
                                        tv_taobao.setTextColor(getResources().getColor(R.color.blue));
                                    } else if (taobao_state.equals("2") || zhima_state.equals("2")) {
                                        tv_taobao.setText("认证中");
                                        taobao_cunt_icon_icon.setEnabled(false);
                                    } else if (taobao_state.equals("3") || zhima_state.equals("3")) {
                                        tv_taobao.setText("认证失败");
                                        tv_taobao.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        tv_taobao.setText("未认证");
                                        tv_taobao.setTextColor(getResources().getColor(R.color.red));
                                    }
                                } else {
                                    tv_taobao.setText("未认证");
                                    tv_taobao.setTextColor(getResources().getColor(R.color.red));
                                }
                                if (!TextUtils.isEmpty(emergency_contact_state)) {
                                    if (emergency_contact_state.equals("0")) {
                                        emergency_icon.setText("未认证");
                                        emergency_icon.setTextColor(getResources().getColor(R.color.red));
                                    } else if (emergency_contact_state.equals("1")) {
                                        emergency_icon.setText("已认证");
                                        the_ontact.setEnabled(false);
                                        emergency_icon.setTextColor(getResources().getColor(R.color.blue));
                                    } else if (emergency_contact_state.equals("2")) {
                                        emergency_icon.setText("认证中");
                                        the_ontact.setEnabled(false);
                                    } else if (emergency_contact_state.equals("3")) {
                                        emergency_icon.setText("认证失败");
                                        emergency_icon.setTextColor(getResources().getColor(R.color.blue));
                                    } else {
                                        emergency_icon.setText("未认证");
                                        emergency_icon.setTextColor(getResources().getColor(R.color.red));
                                    }
                                } else {
                                    emergency_icon.setText("未认证");
                                    emergency_icon.setTextColor(getResources().getColor(R.color.red));
                                }


                            } else if (response.getCode().equals("9")) {
                                Intent intent = new Intent(ProcessActivity.this,
                                       WorthPurseUtil.getZhiddActivity().getClass());
                                startActivity(intent);
                                showShortToast1("您的账号在其他设备登录,请重新登录");
                                finish();
                            } else {
                                showShortToast1(response.getMsg());
                            }
                        }
                        else if (response.getCode().equals("9")) {
                            Intent intent = new Intent(ProcessActivity.this,
                                    WorthPurseUtil.getZhiddActivity().getClass());
                            startActivity(intent);
                            showShortToast1("您的账号在其他设备登录,请重新登录");
                            finish();
                        }
                    }
                    break;
            }
        }
    };
}